const Router = require("koa-router");
const router = new Router({ prefix: "/goods" });

const { auth, hadAdminPermission } = require("../middleware/auth.middleware");
const { validator } = require("../middleware/goods.middleware");
const {
    upload,
    creat,
    update,
    remove,
    restore,
    findAll,
} = require("../controller/goods.controller");

// 无效 定义中间件函数，接受一个参数，即文件格式数组
const fileFormatMiddleware = (formats) => {
    return async (ctx, next) => {
        ctx.request.formidable = {
            //使用展开语法将ctx.request.formidable对象中的所有属性添加到新的对象中
            ...ctx.request.formidable,
            //文件上传的回调函数
            onFileBegin: (name, file) => {
                const extension = path.extname(file.name);
                if (!formats.includes(extension)) {
                    throw new Error(
                        `Invalid file extension. Only ${formats.join(
                            ", "
                        )} are allowed.`
                    );
                }
            },
        };
        await next();
    };
};

//商品图片上传接口
router.post("/upload", auth, hadAdminPermission, upload);

//发布商品接口
router.post("/", auth, hadAdminPermission, validator, creat);

//更新商品接口
router.put("/:id", auth, hadAdminPermission, validator, update);

//硬删除接口
// router.delete('/:id', auth, hadAdminPermission, remove)

//软删除（下架）
router.post("/:id/off", auth, hadAdminPermission, remove);
router.post("/:id/on", auth, hadAdminPermission, restore);

//获取商品列表
router.get('/', findAll)
//模糊查询
 router.get('/:goods_name', findAll)

module.exports = router;
